//
//  YDRefreshControl.swift
//  YDWeibo01
//
//  Created by suibian on 16/8/17.
//  Copyright © 2016年 iitcast. All rights reserved.
//

import UIKit
enum YDRefreshControlState: Int {
    // 正常
    case Normal = 0
    // 下拉中
    case Pulling = 1
    // 刷新中
    case Refreshing = 2
}

//控件的高度
private let refreshControlH:CGFloat = 50

class YDRefreshControl: UIRefreshControl {
//记录滑动视图
    var scrollView:UIScrollView?
    // 记录状态
    var hmState:YDRefreshControlState = .Normal{
        didSet{
            switch hmState{
            case .Normal:
                messageLabel.text = "正常"
                // 只有上个状态为刷新中 才减去scrollView 顶部滑动的距离
                if oldValue == .Refreshing {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.scrollView?.contentInset.top -= refreshControlH
                        }, completion: { (_) -> Void in
                            
                    })
                }
                
            case .Pulling:
                messageLabel.text = "下拉中"
            case .Refreshing:
                messageLabel.text = "刷新中"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    // 只有当前状态为刷新中 才加上scrollView 顶部滑动的距离
                    self.scrollView?.contentInset.top += refreshControlH
                    }, completion: { (_) -> Void in
                        // 告知外界刷新
                        self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
                })
            }
        }
    }

    
   override init(frame: CGRect) {
        super.init(frame:CGRect(x: 0, y: -refreshControlH, width: KSCREENW, height: refreshControlH))
        setUpUI()
    
    }

   required init?(coder aDecoder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
   }
    override func willMoveToSuperview(newSuperview: UIView?) {
        guard let scrollView = newSuperview as? UIScrollView else{
        return
        }
        //    注册观察着
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
    }
//    观察者的实现
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        记录scrollView 的滚动
        let contentOffsetY = self.scrollView!.contentOffset.y
        // 代表拖动中
        if scrollView!.dragging {
            if contentOffsetY > -114 && hmState == .Pulling{
                print("正常")
                hmState = .Normal
            }else if contentOffsetY <= -114 && hmState == .Normal{
                print("下拉中")
                hmState = .Pulling
            }
            
        }else {
            // 松手了
            if hmState == .Pulling {
                hmState = .Refreshing
                print("刷新中")
            }
        }
    }

    
//    设置UI
    private func setUpUI(){
        backgroundColor = AppThemeColor
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        
        // 添加约束
        /*
        - 01 约束的对象
        - 02 约束的条件
        - 03 关系
        - 04 相对的对象
        - 05 约束的条件
        - 06 倍数
        - 07 偏移量
        */
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        
    }
    // MARK: - 懒加载控件
    private lazy var messageLabel: UILabel = {
        let lab = UILabel()
        lab.text = "正常"
        lab.textColor = UIColor.whiteColor()
        lab.font = UIFont.systemFontOfSize(15)
        return lab
    }()
    // KVO移除
    deinit{
        self.scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
}

extension YDRefreshControl: UIScrollViewDelegate {
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
    }
}


